<!-- 会员 - 积分调整【积分商城】 - 弹窗组件 -->
<template>
  <div>
    <CustomDialog
      v-model:visible="isShowDialog"
      top="2vh"
      curent-class="integral-adjustment-dialog"
    >
      <div class="dialog-content">
        <div class="title">积分调整</div>
        <div class="current-points" v-if="currentPoints !== undefined">
          当前积分余额：<span class="points-value">{{ currentPoints }}分</span>
        </div>
        <div class="form-box">
          <div class="form-item">
            <div class="desc">调整方式</div>
            <el-select
              class="select"
              v-model="form.points.mode"
              placeholder="请选择调整方式"
              clearable
            >
              <el-option
                v-for="(item, index) in adjustTypeOptions"
                :key="item.value + index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="form-item">
            <div class="desc">调整积分</div>
            <div class="input-container">
              <el-input
                class="input"
                v-model="form.points.value"
                :placeholder="
                  form.points.mode === 'dec' ? `最多可减少${maxReducePoints}分` : '请输入调整积分'
                "
                clearable
                :class="{ 'error-input': !isValidPointsInput && form.points.value }"
              ></el-input>
              <div class="input-tip" v-if="form.points.mode === 'dec' && form.points.value">
                <span v-if="isValidPointsInput" class="tip-success">✓ 有效</span>
                <span v-else class="tip-error">✗ 超出可用积分</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 数字键盘组件 -->
      <NumberKeyboard
        v-model:keyword="form.points.value"
        @onInputKeyboard="onInputKeyboard"
        @onCancel="handleClearInput"
        @onConfirm="onConfirm"
        :loading="keyboardLoading"
      />
    </CustomDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'
import { formTestFun } from '@/utils/toolsValidate'
import { pointsEdit } from '@/api/member'

interface Props {
  visible: boolean
  inputKeyword?: string
  memberId: string
  currentPoints?: number // 当前积分余额
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'update:inputKeyword', value: string): void
  (e: 'onConfirm'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  inputKeyword: '',
  memberId: '',
  currentPoints: 0
})

const emit = defineEmits<Emits>()

// 控制弹窗显示
const isShowDialog = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
})

// 控制输入关键词
const inputKeyword = computed({
  get: () => props.inputKeyword,
  set: val => emit('update:inputKeyword', val)
})

// 表单数据
const form = reactive({
  target: 'points', // 修改内容
  points: {
    mode: '', // 调整类型
    value: '', // 修改数量
    remark: '' // 修改备注
  }
})

// 调整方式的枚举数组
const adjustTypeOptions = ref([
  {
    value: 'inc',
    label: '增加'
  },
  {
    value: 'dec',
    label: '减少'
  },
  {
    value: 'final',
    label: '修改最终数量'
  }
])

// 数字键盘loading状态
const keyboardLoading = ref(false)

// 计算最大可减少的积分数量
const maxReducePoints = computed(() => {
  return props.currentPoints || 0
})

// 验证积分输入是否有效
const isValidPointsInput = computed(() => {
  if (!form.points.value) return true // 空值认为是有效的

  const inputValue = parseFloat(form.points.value)
  if (isNaN(inputValue) || inputValue <= 0) return false

  // 如果是减少积分，检查是否超过当前积分余额
  if (form.points.mode === 'dec' && inputValue > maxReducePoints.value) {
    return false
  }

  return true
})

// 清空输入框
const handleClearInput = () => {
  form.points.value = ''
}

// 接收数字键盘传过来的关键词
const onInputKeyboard = (val: string) => {
  form.points.value = val
}

// 确认提交事件
const onConfirm = () => {
  // testForm对象的value值只判断是否为true即可
  const testForm = {
    请输入调整方式: form.points.mode,
    请输入调整积分: form.points.value
  }
  if (formTestFun(testForm)) return

  // 验证积分输入是否有效
  if (!isValidPointsInput.value) {
    if (form.points.mode === 'dec') {
      ElMessage.error(`减少积分不能超过当前积分余额（${maxReducePoints.value}分）`)
    } else {
      ElMessage.error('请输入有效的积分数量')
    }
    return
  }

  keyboardLoading.value = true
  const datas = {
    form: form,
    userId: props.memberId
  }

  pointsEdit(datas)
    .then(res => {
      if (res.status === 200) {
        ElMessage.success('操作成功')
        emit('update:visible', false)
        emit('onConfirm')
        // 重置表单
        form.target = 'points'
        form.points.mode = ''
        form.points.value = ''
        form.points.remark = ''
      }
    })
    .catch(error => {
      console.error('积分调整失败:', error)
    })
    .finally(() => {
      keyboardLoading.value = false
    })
}
</script>

<style lang="scss" scoped>
:deep(.el-input__inner) {
  border-radius: 12px;
}

.dialog-content {
  .title {
    font-size: 20px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #333333;
  }

  .current-points {
    text-align: center;
    margin: 15px 0;
    font-size: 14px;
    color: #666666;

    .points-value {
      color: #409eff;
      font-weight: 600;
    }
  }

  .form-box {
    padding: 0 14px;
    margin-bottom: 60px;

    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 30px;

      .desc {
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
        margin-right: 20px;
      }

      .input-container {
        width: 420px;
        display: flex;
        flex-direction: column;

        .input {
          width: 100%;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333333;
          outline: none;
          border: none;

          &.error-input {
            :deep(.el-input__inner) {
              border-color: #f56c6c;
            }
          }
        }

        .input-tip {
          margin-top: 5px;
          font-size: 12px;

          .tip-success {
            color: #67c23a;
          }

          .tip-error {
            color: #f56c6c;
          }
        }
      }

      .select {
        width: 420px;
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: #333333;
        outline: none;
        border: none;
      }
    }
  }
}
</style>

<style lang="scss">
.integral-adjustment-dialog {
  max-height: unset !important;
}
</style>
